﻿<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item
          label="商品主图"
          prop="good_img"
          :rules="{ required: true, message: '商品主图不能为空', trigger: 'blur'}"
        >
          <el-upload
            :action="uploadUrl"
            :file-list="form.good_img"
            multiple
            name="file"
            list-type="picture-card"
            :on-success="handlePictureSuccess"
            :on-preview="handlePicturePreview"
            :before-upload="beforePictureUpload"
            :on-remove="handlePictureRemove"
          >
            <i class="el-icon-plus"/>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5M</div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item
          label="商品名称"
          prop="productName"
          :rules="{ required: true, message: '商品名称不能为空', trigger: 'blur'}"
        >
          <el-input v-model="form.productName" placeholder="请输入商品名称"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="款号"
              prop="brandName"
              :rules="{ required: true, message: '款色不能为空', trigger: 'blur'}"
            >
              <el-input v-model="form.brandName" placeholder="请输入款号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="分类信息"
              prop="productCategoryId"
              :rules="{ required: true, message: '分类信息不能为空', trigger: 'blur'}"
            >
              <el-cascader
                placeholder="试试搜索：上装"
                :options="categoryItem"
                filterable
                :value="form.productCategoryId"
                @change="handleCategoryChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="品牌主题"
              prop="productCategoryId"
              :rules="{ required: true, message: '品牌主题不能为空', trigger: 'blur'}"
            >
              <el-select v-model="form.seasonsId" placeholder="品牌主题">
                <el-option
                  v-for="(item, index) in seasonsCategory"
                  :key="index"
                  :label="item.seasonsName"
                  :value="item.seasonsId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="批发价格"
              prop="productPrice"
              :rules="{ required: true, message: '批发价格不能为空', trigger: 'blur'}"
            >
              <el-input v-model="form.productPrice" type="number" min="1" placeholder="请输入批发价格"/>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item-->
          <!--              label="库存"-->
          <!--              prop="productStock"-->
          <!--              :rules="{ required: true, message: '库存不能为空', trigger: 'blur'}"-->
          <!--            >-->
          <!--              <el-input v-model="form.productStock" type="number" min="1" placeholder="请输入库存"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌货">
              <el-switch v-model="form.isBrand"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="潮流">
              <el-switch v-model="form.isTrend"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐">
              <el-switch v-model="form.isRecommend"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          label="详情图"
          prop="detail_img"
          :rules="{ required: true, message: '详情图不能为空', trigger: 'blur'}"
        >
          <el-upload
            :action="uploadUrl"
            :file-list="form.detail_img"
            multiple
            name="file"
            list-type="picture-card"
            :on-success="handleDetailSuccess"
            :on-preview="handlePicturePreview"
            :before-upload="beforePictureUpload"
            :on-remove="handleDetailRemove"
          >
            <i class="el-icon-plus"/>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5M</div>
          </el-upload>
          <el-dialog :visible.sync="dialogDetailVisible">
            <img width="100%" :src="dialogDetailImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="form.description" type="textarea" placeholder="请输入商品描述"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.note" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
        <el-form-item label="颜色尺寸">
          <div class="spec">
            <div class="spec-title">
              <div class="nav">
                <p>颜色</p>
              </div>
              <div class="nav">
                <p>尺寸</p>
              </div>
              <div class="nav">
                <p>库存</p>
              </div>
              <div class="nav">
                <p>操作</p>
              </div>
            </div>
            <div v-if="tableData.length>0" class="spec-body">
              <div v-for="(item,index) in tableData" :key="index" class="spec-box">
                <div class="spec-left">
                  <div class="spec-tr">
                    <div class="spec-td">
                      <el-input v-model="item.color" placeholder="请输入颜色"/>
                      <el-button size="mini" type="danger" @click="deleteColor(item)">删除颜色</el-button>
                    </div>
                  </div>
                </div>
                <div class="spec-right">
                  <div v-for="(sizeItem,sizeIndex) in item.size" :key="sizeIndex" class="spec-tr">
                    <div class="spec-td">
                      <el-input v-model="sizeItem.size" placeholder="请输入尺寸"/>
                    </div>
                    <div class="spec-td">
                      <el-input v-model="sizeItem.stock" placeholder="请输入库存" type="number"/>
                    </div>
                    <div class="spec-td">
                      <el-button size="mini" type="danger" @click="deleteSize(item, sizeItem)">删除尺寸</el-button>
                      <el-button size="mini" type="primary" @click="addSize(item, sizeItem)">添加尺寸</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="spec-note">
              <p>暂无规格信息</p>
            </div>
          </div>
          <el-button size="mini" type="success" class="colorBtn" @click="addColor">添加颜色</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" :disabled="clickDisabled" @click="onSubmit('form')">立即保存</el-button>
          <el-button size="small" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { createProduct, getCategoryChildren, getProduct, getSeasonsCategory, updateProduct } from '@/api/Product'

const defaultSettings = require('@/settings.js')
export default {
  data() {
    return {
      tableData: [],
      selectedOptions: [],
      imageUrl: '',
      clickDisabled: false,
      dialogVisible: false,
      dialogDetailVisible: false,
      dialogDetailImageUrl: '',
      dialogImageUrl: '',
      uploadUrl: defaultSettings.uploadUrl,
      categoryItem: [],
      categorySelectItem: [],
      form: {
        productId: '',
        productName: '',
        brandName: '',
        productCategoryId: '',
        note: '',
        description: '',
        good_img: [],
        detail_img: [],
        productPrice: '',
        productStock: 9999,
        isBrand: false,
        isTrend: false,
        seasonsId: '',
        isRecommend: false
      },
      rules: {},
      seasonsCategory: []
    }
  },
  created() {
    getCategoryChildren().then(res => {
      this.categoryItem = res.data
    })
    if (this.$route.query.productId) {
      this.form.productId = this.$route.query.productId
      this.getProductContent()
    }
    getSeasonsCategory().then(res => {
      this.seasonsCategory = res.data
    })
  },
  methods: {
    cancel() {
      this.$router.push('/product/list')
    },
    getProductContent: function() {
      getProduct({ id: this.form.productId }).then(res => {
        if (res.code === 200) {
          const goodImage = []
          if (res.data.mainPic) {
            res.data.goodImage.forEach((item, index) => {
              goodImage.push({
                uid: item.index,
                url: item
              })
            })
          }
          const detailSImage = []
          if (res.data.goodContentImage) {
            res.data.goodContentImage.forEach((item, index) => {
              detailSImage.push({
                uid: item.index,
                url: item
              })
            })
          }
          this.form.good_img = goodImage
          this.form.detail_img = detailSImage
          this.form.productName = res.data.productName
          this.form.brandName = res.data.brandName
          this.form.productCategoryId = res.data.productCategoryId
          this.form.productStock = res.data.productStock
          this.form.productPrice = res.data.productPrice / 100
          this.form.isBrand = res.data.isBrand > 0
          this.form.isRecommend = res.data.isRecommend > 0
          this.form.isTrend = res.data.isTrend > 0
          this.form.note = res.data.note
          this.form.seasonsId = res.data.seasonsId
          this.form.description = res.data.description

          const sku = res.data.sku
          const colorItem = []
          const tableData = []
          sku.forEach(item => {
            const indexOf = colorItem.indexOf(item.skuColour)
            if (indexOf === -1) {
              colorItem.push(item.skuColour)
            }
          })
          colorItem.forEach((color, index) => {
            tableData.push({
              color: color,
              size: []
            })
            sku.forEach(item => {
              if (item.skuColour === color) {
                tableData[index].size.push({
                  id: item.skuId,
                  size: item.skuSize,
                  stock: item.stock
                })
              }
            })
          })
          this.tableData = tableData
        } else {
          this.$message.error('网络错误')
        }
      })
    },
    addColor() {
      this.$prompt('请输入颜色', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        let colorBtn = true
        this.tableData.forEach(res => {
          if (res.color === value) {
            colorBtn = false
          }
        })
        if (colorBtn) {
          const sizeData = []
          sizeData.push({
            id: 0,
            size: 'S',
            stock: 9999
          }, {
            id: 0,
            size: 'M',
            stock: 9999
          }, {
            id: 0,
            size: 'L',
            stock: 9999
          }, {
            id: 0,
            size: 'XL',
            stock: 9999
          }, {
            id: 0,
            size: 'XXL',
            stock: 9999
          }, {
            id: 0,
            size: 'XXXl',
            stock: 9999
          })
          this.tableData.push({
            color: value,
            size: sizeData
          })
        } else {
          this.$message.error('颜色已存在，请不要重复添加')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    deleteColor(event) {
      const indexOf = this.tableData.indexOf(event)
      if (indexOf !== -1) {
        this.tableData.splice(indexOf, 1)
      }
    },
    deleteSize(event, size) {
      const indexOf = this.tableData.indexOf(event)
      if (indexOf !== -1) {
        // this.tableData.splice(indexOf, 1)
        const sizeIndex = this.tableData[indexOf].size.indexOf(size)
        if (sizeIndex !== -1) {
          this.tableData[indexOf].size.splice(sizeIndex, 1)
        }
      }
    },
    addSize(event, size) {
      const indexOf = this.tableData.indexOf(event)
      this.tableData[indexOf].size.push({
        id: 0,
        size: '',
        stock: 9999
      })
    },
    onSubmit(formName) {
      const mainPic = []
      const detailsPic = []
      this.form.good_img.forEach(function(item, index) {
        mainPic.push(item.url)
      })
      this.form.detail_img.forEach(res => {
        detailsPic.push(res.url)
      })
      if (this.tableData.length > 0) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let stock = 0
            this.tableData.forEach(item => {
              item.size.forEach(size => {
                stock = stock + size.stock
              })
            })
            const form = {
              productName: this.form.productName,
              brandName: this.form.brandName,
              note: this.form.note,
              description: this.form.description,
              productStock: stock,
              productCategoryId: this.form.productCategoryId,
              isBrand: this.form.isBrand ? 1 : 0,
              isRecommend: this.form.isRecommend ? 1 : 0,
              isTrend: this.form.isTrend ? 1 : 0,
              mainPic: mainPic.join(','),
              detailsPic: detailsPic.join(','),
              productPrice: this.form.productPrice * 100,
              seasonsId: this.form.seasonsId,
              sku: JSON.stringify(this.tableData)
            }
            if (this.form.productId) {
              form.productId = this.form.productId
              updateProduct(form).then(res => {
                if (res.code === 200) {
                  this.$message.success('保存成功')
                  this.cancel()
                } else {
                  this.$message.error('网络错误')
                  this.clickDisabled = false
                }
              })
            } else {
              createProduct(form).then(res => {
                if (res.code === 200) {
                  this.$message.success('保存成功')
                  this.cancel()
                } else {
                  this.$message.error('网络错误')
                  this.clickDisabled = false
                }
              })
            }
            console.log(form)
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$message.error('请输入您的商品规格信息')
      }
      console.log(this.tableData)
    },
    beforePictureUpload(file) {
      const typeItem = ['image/jpeg', 'image/png']
      const isJPG = typeItem.indexOf(file.type)
      const isLt2M = file.size / 1024 / 1024 < 5
      if (isJPG < 0) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    },
    handlePicturePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handlePictureSuccess(res, file, fileList) {
      const fileImgList = []
      fileList.forEach(item => {
        if (item.response) {
          fileImgList.push({
            uid: item.uid,
            url: item.response.data
          })
        } else {
          fileImgList.push({
            uid: item.uid,
            url: item.url
          })
        }
      })
      this.form.good_img = fileImgList
    },
    handlePictureRemove(file) {
      if (file.status === 'success') {
        let index = -1
        for (let i = 0; i < this.form.good_img.length; i++) {
          if (this.form.good_img[i].url === file.url) {
            index = i
          }
        }
        if (index !== -1) {
          this.form.good_img.splice(index, 1)
        }
      }
    },
    handleCategoryChange(event) {
      this.form.productCategoryId = event[1]
    },
    handleDetailSuccess(res, file, fileList) {
      const fileImgList = []
      fileList.forEach(item => {
        if (item.response) {
          fileImgList.push({
            uid: item.uid,
            url: item.response.data
          })
        } else {
          fileImgList.push({
            uid: item.uid,
            url: item.url
          })
        }
      })
      this.form.detail_img = fileImgList
    },
    handleDetailRemove(file) {
      if (file.status === 'success') {
        let index = -1
        for (let i = 0; i < this.form.detail_img.length; i++) {
          if (this.form.detail_img[i].url === file.url) {
            index = i
          }
        }
        if (index !== -1) {
          this.form.detail_img.splice(index, 1)
        }
      }
    }
  }

}
</script>
<style lang="scss">
.colorSku {

  .el-input {
    width: 60%;
    float: left;
  }

  .el-button {
    width: 15%;
    float: left;
    padding: 12px 0;
    margin-left: 10px;
  }
}

.table {
  width: 100%;
  border: 1px solid #cccccc;

  .t-tr {

    .t-th {
      flex: 1;
      padding: 10px;
      line-height: 25px;
      font-size: 14px;
      border-right: 1px solid #cccccc;

      &:last-child {
        border-right: 0 solid #cccccc;
      }

    }

    .t-td {
      flex: 1;
      text-align: center;
      font-size: 14px;
      padding: 13px;
      border-right: 1px solid #cccccc;
      border-top: 1px solid #cccccc;

      &:last-child {
        border-right: 0 solid #cccccc;
      }
    }

    &:last-child {
    }
  }
}

.spec {
  width: 100%;
  margin-top: 10px;

  .spec-title {
    width: 100%;
    display: flex;
    border: 1px solid #cccccc;

    .nav {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 10px;
      height: 50px;

      p {
        font-size: 14px;
        margin: 0;
        line-height: 20px;
        font-weight: bold;
      }
    }
  }

  .spec-body {
    width: 100%;
    overflow: hidden;

    .spec-box {
      width: 100%;
      overflow: hidden;
      border-bottom: 1px solid #cccccc;
      border-right: 1px solid #cccccc;
      border-left: 1px solid #cccccc;
    }

    .spec-left {
      float: left;
      width: 25%;
      display: flex;
      align-self: center;
      align-items: center;
      height: 100%;

      .spec-tr {
        display: flex;
        width: 100%;

        .spec-td {
          padding: 10px;
          flex: 1;
          align-items: center;
          justify-content: center;
          align-self: center;
        }
      }
    }

    .spec-right {
      float: left;
      width: 75%;
      height: 100%;

      .spec-tr {
        width: 100%;
        display: flex;

        .spec-td {
          padding: 10px;
          border-left: 1px solid #cccccc;
          border-bottom: 1px solid #cccccc;
          flex: 1;
          text-align: center;
          align-items: center;
          justify-content: center;
          align-self: center;
        }

        &:last-child {
          .spec-td {
            border-bottom: 0;
          }
        }
      }
    }
  }

  .spec-note {
    width: 100%;
    padding: 20px;
    border-bottom: 1px solid #cccccc;
    border-right: 1px solid #cccccc;
    border-left: 1px solid #cccccc;
    text-align: center;

    p {
      font-size: 14px;
      color: #777777;
      margin: 0;
    }
  }
}

.colorBtn {
  position: absolute;
  left: -90px;
  top: 40px;
}

</style>
